package com.taibo.giflib.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;

/**
 * @author zgl
 * 日期：2022/6/9
 * 时间：16:26
 */
public class GifView extends ImageView implements Runnable, LifecycleObserver {
    private String gifPath = null;

    private Bitmap bitmap;
    private int maxLength;
    private int currentLength;
    private GifHandler gifHandler;

    private boolean isRun;
    private boolean isPause;
    private float mSpeed;

    public GifView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        if (context instanceof LifecycleOwner) {
            ((LifecycleOwner) context).getLifecycle().addObserver(this);
        }
    }

    @Override
    public void run() {
        if (isRun && gifPath != null && !"".equals(gifPath)) {
            if (!isPause) {
                currentLength++;
                if (currentLength >= maxLength) {
                    currentLength = 0;
                }
                long delayTime = gifHandler.renderFrame(bitmap, currentLength);
                setImageBitmap(bitmap);
                postDelayed(this, (int) (delayTime * mSpeed));
            } else {
                postDelayed(this, 20);
            }
        }
    }

    /**
     * 设置速度倍率，越大越慢
     *
     * @param speed
     */
    public void setSpeed(float speed) {
        mSpeed = speed;
    }

    /**
     * 设置gif路径
     *
     * @param path
     */
    public void setGifPath(String path) {
        if (gifPath != null && gifPath.equals(path)) {
            return;
        }
        removeCallbacks(this);
        gifPath = path;

        isRun = true;
        gifHandler = new GifHandler(gifPath);
        int width = gifHandler.getWidth();
        int height = gifHandler.getHeight();

        bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        maxLength = gifHandler.getLength();

        long delayTime = gifHandler.renderFrame(bitmap, 0);
        setImageBitmap(bitmap);
        postDelayed(this, delayTime);
    }

    public void setRun(boolean isRun) {
        this.isRun = isRun;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume() {
        isPause = false;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause() {
        isPause = true;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {
        isRun = false;
    }
}
